﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleVigenereMeter
{
    public class Kasiski
    {
        private Dictionary<string, ArrayList> result = new Dictionary<string, ArrayList>();
        private string text;

        public Kasiski(string text)
        {
            if (text.Length < 1)
            {
                throw new Exception("text is empty.");
            }

            this.text = text;
        }

        public Dictionary<string, ArrayList> SearchRedundantString(int length)
        {
            int textLength = text.Length;
            int bound = textLength - length;
            string sub;
            ArrayList searchResult;

            for (int i = 0; i < bound; ++i)
            {
                sub = text.Substring(i, length);
                if (!result.ContainsKey(sub))
                {
                    searchResult = BoyerMore.Match(text.Substring(i), sub);
                    if (searchResult.Count > 1)
                    {
                        UpdateSearchResult(searchResult, i);
                        result.Add(sub, searchResult);
                    }
                }
            }

            return result;
        }

        private static void UpdateSearchResult(ArrayList searchResult, int i)
        {
            for (int j = 0; j < searchResult.Count; ++j)
            {
                searchResult[j] = (int)searchResult[j] + i;
            }
        }

        public override string ToString()
        {
            int length = result.Count;
            StringBuilder sb = new StringBuilder();
            sb.Append("Kasiski\n");
            sb.Append("Number result : " + length + "\n");

            foreach (KeyValuePair<String, ArrayList> value in result)
            {
                sb.Append("Key " + value.Key + " (Length : "+ value.Value.Count +") :\n");
                sb.Append(Helper.ToString(value.Value) + "\n");
            }

            return sb.ToString();
        }
    }
}